package com.cg.leetcode;

import org.junit.Test;

/**
 * @program: LeetCode->LeetCode_974
 * @description: 974. 和可被 K 整除的子数组
 * @author: cg
 * @create: 2021-08-19 18:13
 **/

public class LeetCode_974 {

    /**
     * 给定一个整数数组 A，返回其中元素之和可被 K 整除的（连续、非空）子数组的数目。
     * <p>
     * 示例：
     * <p>
     * 输入：A = [4,5,0,-2,-3,1], K = 5
     * 输出：7
     * 解释：
     * 有 7 个子数组满足其元素之和可被 K = 5 整除：
     * [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]
     * <p>
     * 提示：
     * 1 <= A.length <= 30000
     * -10000 <= A[i] <= 10000
     * 2 <= K <= 10000
     */

    @Test
    public void test974() {
        int A[] = {4, 5, 0, -2, -3, 1};
        int K = 5;
        System.out.println(subarraysDivByK(A, K));
    }

    public int subarraysDivByK(int[] nums, int k) {
        int count = 0, length = nums.length, sum = 0;
        int[] map = new int[k];
        map[0] = 1;
        for (int i = 1; i <= length; i++) {
            sum += nums[i - 1];
            int key = (sum % k + k) % k;
            count += map[key]++;
        }
        return count;
    }

}
